<script setup>
	import { nextTick, ref, computed } from 'vue'
	import { io } from 'socket.io-client'
	import { useUserStore } from '@/stores/user'
	import { orderDetailApi } from '@/services/consult.js'

	// 引入患者信息组件
	import patientInfo from './components/patient-info.vue'

	// 引入通知消息组件
	import notifyInfo from './components/notify-info.vue'

	// 引入通知消息组件
	import messageInfo from './components/message-info.vue'

	// 引入处方消息组件
	import prescriptionInfo from './components/prescription-info.vue'

	// 引入处方消息组件
	import rateInfo from './components/rate-info.vue'

	import roomStatus from './components/room-status.vue'
	const scrollTop = ref(0)

	const str = computed(() => {
		return scrollTop.value
	})
	// 用户登录信息（不具有响应式）
	const {
		setBasicInfo: { token, id: userId },
	} = useUserStore()

	// 获取地址中的参数
	const props = defineProps({
		orderId: String,
	})
	// 消息列表
	const messageList = ref([])
	// 文字消息
	const textMessage = ref('')
	// 问诊订单详情
	const orderDetail = ref({})
	console.log(orderDetail.value)
	// 建立 socket 连接
	const socket = io('https://consult-api.itheima.net', {
		auth: { token: 'Bearer ' + token },
		query: { orderId: props.orderId },
		transports: ['websocket', 'polling'],
		timeout: 5000,
	})
	// 测试socket连接
	socket.on('connect', async () => {
		console.log('连接建立成功')
		// 接收消息列表
		socket.on('chatMsgList', ({ code, data }) => {
			// 没有返回数据
			if (code !== 10000) return
			// 提取列表数据
			const tempList = []

			data.forEach(({ createTime, items }) => {
				// 追加到消息列表中
				tempList.push(
					// 构造一条数据，显示时间节点
					{
						msgType: 31,
						msg: { content: createTime },
						id: createTime,
					},
					...items
				)
			})

			// 追加到消息列表中
			messageList.value.unshift(...tempList)
		})
		await nextTick()
		// 要等待视图更新完成后，在设置滚动距离
		scrollTop.value = 10000
		console.log(scrollTop.value)
	})
	// 监听订单状态变化
	socket.on('statusChange', getOrderDetail)

	// 接收消息
	socket.on('receiveChatMsg', async (message) => {
		// 修改消息为已读
		socket.emit('updateMsgStatus', message.id)
		// 接收到的消息追加到消息列表中
		messageList.value.push(message)
		await nextTick()
		scrollTop.value += 10000
	})

	// 发送文字消息
	function onInputConfirm() {
		// if (!textMessage.vlaue) return uni.utils.toast('发送内容不能为空!')
		// 发送消息
		socket.emit('sendChatMsg', {
			// 当前登录用户的ID
			from: userId,
			to: orderDetail.value?.docInfo?.id,
			msgType: 1,
			msg: {
				content: textMessage.value,
			},
		})
		textMessage.value = ''
	}
	// 发送图片消息
	async function onImageButtonClick() {
		// 是否在问诊状态中...
		if (orderDetail.value.status !== 3) {
			return uni.utils.toast('医生当前不在线!')
		}
		// 上传图片到 uniCloud
		uniCloud.chooseAndUploadFile({
			type: 'image',
			count: 1,
			extension: ['.jpg', '.png', '.gif'],
			success: ({ tempFiles }) => {
				// 上传成功的图片
				const picture = {
					id: tempFiles[0].lastModified,
					url: tempFiles[0].url,
				}
				// 发送消息
				socket.emit('sendChatMsg', {
					from: userId,
					to: orderDetail.value?.docInfo?.id,
					msgType: 4,
					msg: { picture },
				})
			},
		})
	}

	// 获取问诊订单详情
	async function getOrderDetail() {
		// 调用接口
		const { code, data, message } = await orderDetailApi(props.orderId)
		console.log(data)
		// 检测接口是否调用成功
		if (code !== 10000) return uni.utils.toast(message)
		// 渲染问诊订单数据

		orderDetail.value = data
	}
	getOrderDetail()

	// 关闭下拉动画交互
	const refreshTrigger = ref(false)
	// 下拉获取历史消息
	function onPullDownRefresh() {
		// 开启下拉交互动画
		refreshTrigger.value = true

		setTimeout(() => {
			// 关闭下拉交互动画
			refreshTrigger.value = false
		}, 1000)
	}
</script>

<template>
	<view class="room-page">
		<room-status
			:status-value="orderDetail.statusValue"
			:countdown="orderDetail.countdown"
			:status="orderDetail.status"
		/>

		<scroll-view
			:scroll-top="10000"
			:refresher-triggered="refreshTrigger"
			@refresherrefresh="onPullDownRefresh"
			refresher-enabled
			refresher-background="#f2f2f2"
			scroll-y
			style="flex: 1; overflow: hidden"
		>
			<view class="message-container">
				<!-- 此处将来填充更多代码... -->
				<template v-for="message in messageList" :key="message.id">
					<!-- 患者信息（21） -->
					<patient-info
						v-if="message.msgType === 21"
						:info="message.msg.consultRecord"
					/>
					<!-- 消息通知 -->
					<notify-info
						v-if="message.msgType >= 31"
						:type="message.msgType"
					>
						{{ message.msg.content }}
					</notify-info>

					<!-- 文字图片消息 -->
					<message-info
						v-if="message.msgType <= 4"
						:info="message"
						:type="message.msgType"
					/>
					<!-- 电子处方 -->
					<prescription-info
						v-if="message.msgType === 22"
						:info="message.msg.prescription"
					/>
					<!-- 医生评价 -->
					<rate-info
						:evaluateDoc="message.msg.evaluateDoc"
						:orderId="props.orderId"
						:docId="orderDetail.docInfo?.id"
						v-if="message.msgType === 23"
					></rate-info>
					<!-- 医生评价（已评价） -->
					<rate-info
						:evaluateDoc="message.msg.evaluateDoc"
						has-evaluate
						v-if="message.msgType === 24"
					/>
					<!-- 此处将来填充更多代码... -->
				</template>
			</view>
		</scroll-view>

		<!-- 发送消息 -->
		<view class="message-bar">
			<template v-if="true">
				<uni-easyinput
					v-model.trim="textMessage"
					:disabled="orderDetail.status !== 3"
					:clearable="false"
					:input-border="false"
					placeholder-style="font-size: 32rpx; color: #c3c3c5;"
					placeholder="问医生"
					@confirm="onInputConfirm"
				/>
				<view class="image-button">
					<uni-icons
						size="40"
						color="#979797"
						type="image"
						@click="onImageButtonClick"
					></uni-icons>
				</view>
			</template>
			<button v-else class="uni-button">咨询其它医生</button>
		</view>
	</view>
</template>

<style lang="scss">
	@import './index.scss';
</style>
